#include "do_server.h"
#include "mjson.h"
#include "head.h"

void do_server(int sockfd,char *rec_buf,sqlite3 *pdb)
{
	//解析数据
	json_object *new_obj = NULL;
	struct json_object *child_object = NULL;

	//把字符串转换为json对象
	new_obj = json_tokener_parse(rec_buf);

	//解析类型
	int type;
	child_object = json_object_object_get(new_obj,"报文类型");
	type = json_object_get_int(child_object);
//	get_obj_mem_string(new_obj,"报文类型",type);
	printf("type = %d\n",type);


	//解析功能
	int  action;
	child_object = json_object_object_get(new_obj,"功能号");
	action = json_object_get_int(child_object);
//	get_obj_mem_string(new_obj,"功能号",action);
	printf("action = %#x\n",action);

	//解析数据长度
	short len;
//	get_obj_mem_string(new_obj,"数据长度",len);
	child_object = json_object_object_get(new_obj,"数据长度");
	len = json_object_get_int(child_object);
	printf("len = %d\n",len);

	//解析数据内容
	json_object *obj_chlid = NULL;
//get_obj_mem_object(new_obj,"数据内容",obj_chlid);
    child_object = json_object_object_get(new_obj,"数据内容");

	char *username;
	char *password;
//	get_obj_mem_string(obj_chlid,"用户名",username);
//	get_obj_mem_string(obj_chlid,"密码",password);
    struct json_object *cc_obj;	
	cc_obj = json_object_object_get(child_object,"用户名");
	username = json_object_get_string(cc_obj);

	cc_obj = json_object_object_get(child_object,"密码");
	password = json_object_get_string(cc_obj);
	printf("username = %s\n",username);
	printf("password = %s\n",password);

	

	if(0xff != type)
		return;
	else
		printf("link to sqlite3\n");

	//注册
	if(0x00 == action)
		do_register(sockfd,pdb,username,password);

	//登录
	if(0x01 == action);
		//do_login(sockfd,rev_bu);
}

int do_register(int sockfd,sqlite3 *pdb,char *_username,char *_password)
{
	printf("do_register----------------\n");
	char *errmsg;
	char buf[1024];
	char **dbresult;
	int nrow = 0,ncolumn = 0;
	char sql[1024] = {0};
	
	//查询用户名是否存在
	sprintf(sql,"select * from user where username='%s';",_username);
	if(sqlite3_get_table(pdb,sql,&dbresult,&nrow,&ncolumn,&errmsg) != 0)
	{
		fprintf(stderr,"sqlite3 get table error : %s.\n",errmsg);
		exit(EXIT_FAILURE);
	}

	//没有这样的用户名  注册
	if(nrow == 0)
	{

		//录入数据库
		bzero(sql,sizeof(sql));
		sprintf(sql,"insert into user values('%s','%s');",_username,_password);
		EXEC_SQL(pdb,sql,errmsg);//封装 sqlite3_exec()		
		printf("ok ........\n");		
	}
	//插入到数据库之后，释放dbresult结果
	sqlite3_free_table(dbresult);


	//封装json数据
	json_object *my_object;
	char *json_string = NULL;

	my_object = json_object_new_object();
	json_object_object_add(my_object,"stateCode",json_object_new_int(nrow));
	json_string = (char *)json_object_to_json_string(my_object);

	json_object_put(my_object);

	int n = 0;
	n = send(sockfd,json_string,strlen(json_string),0);
	if(n < 0)
	{
		perror("failed to send\n");
		return 0;
	}

	return 1;
}

#if 0
void do_login(int sockfd)
{
	printf("do_login");
}

#endif

